package com.aps.apspda.base;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.aps.apspda.utils.ActivityManager;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.ToastUtils;

/**
 * @author lx
 * @date 2018/4/19
 * @desc
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static CrashHandler sInstance = null;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Context mContext;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        if (sInstance == null) {
            synchronized (CrashHandler.class) {
                if (sInstance == null) {
                    synchronized (CrashHandler.class) {
                        sInstance = new CrashHandler();
                    }
                }
            }
        }
        return sInstance;
    }

    /**
     * 初始化默认异常捕获
     *
     * @param context context
     */
    public void init(Context context) {
        mContext = context;
        // 获取默认异常处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 将此类设为默认异常处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (!handleException(e)) {
            // 未经过人为处理,则调用系统默认处理异常,弹出系统强制关闭的对话框
            if (mDefaultHandler != null) {
                mDefaultHandler.uncaughtException(t, e);
            }
        } else {
            // 已经人为处理,系统自己退出
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
            PendingIntent restartIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
            ActivityManager.getActivityManager().AppExit(mContext);
        }
    }

    /**
     * 是否人为捕获异常
     *
     * @param e Throwable
     * @return true:已处理 false:未处理
     */
    private boolean handleException(Throwable e) {
        if (e == null) {// 异常是否为空
            return false;
        }
        new Thread() {// 在主线程中弹出提示
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext,"程序出现异常，后台正在重启，请稍后",3000).show();
                Looper.loop();
            }
        }.start();
//        collectErrorMessages();
        AppUtils.saveErrorMessages(e, "系统崩溃");
        return true;
    }

//    /**
//     * 1.收集错误信息
//     */
//    private void collectErrorMessages() {
//        PackageManager pm = mContext.getPackageManager();
//        try {
//            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
//            if (pi != null) {
//                String versionName = TextUtils.isEmpty(pi.versionName) ? "null" : pi.versionName;
//                String versionCode = "" + pi.versionCode;
//                mMessage.put("versionName", versionName);
//                mMessage.put("versionCode", versionCode);
//            }
//            // 通过反射拿到错误信息
//            Field[] fields = Build.class.getFields();
//            if (fields != null && fields.length > 0) {
//                for (Field field : fields) {
//                    field.setAccessible(true);
//                    try {
//                        mMessage.put(field.getName(), field.get(null).toString());
//                    } catch (IllegalAccessException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//    }
}
